define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'project/index' + location.search,
                    add_url: 'project/add',
                    edit_url: 'project/edit',
					pay_url: 'project/pay',
                    del_url: 'project/del',
                    table: 'project',
                }
            });

            var table = $("#table");
			
			//当表格数据加载完成时
			table.on('load-success.bs.table', function (e, data) {
				//这里可以获取从服务端获取的JSON数据
				$("#title").html(data.year+'年度招标采购项目统计');
			});
			
			var queryparams = '';
			
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
				search: false,
				searchFormVisible: true,
				rowStyle:function(row,index){
					var rowstyle = {css:{}};
					if(row.status != 3)
					{
						rowstyle.css.color = 'red';
					}
					if(index%2 == 0)
					{
						rowstyle.css['background-color'] = "#c3ebd1";
					}
					
					return rowstyle;
				},
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('序号'), sortable: true, searchable:false, formatter: function(value, row, index){
							var pageNumber = table.bootstrapTable('getOptions').pageNumber;
							var pageSize = table.bootstrapTable('getOptions').pageSize;
							return ++index + (pageNumber-1)*pageSize;
						}},
						{field: 'serialnumber', title: __('项目编号'), operate: 'LIKE', align:'left'},
						{field: 'budgetyear', title: __('预算年度'), operate: 'LIKE', align:'left'},
                        {field: 'name', title: __('项目名称'), operate: 'LIKE'},
						{field: 'depart.name', title: __('采购科室'), searchable:false, visible:false},
						{field: 'contacter', title: __('联系人'), searchable:false, visible:false},
						{field: 'contactphone', title: __('联系电话'), searchable:false, visible:false},
						{field: 'procuretype', title: __('采购方式'), searchList: {1: __('公开招标'), 2: __('邀请招标'), 3: __('竞争性谈判'), 4: __('竞争性磋商'), 5: __('单一来源采购'), 6: __('询价'), 7: __('直接签订'), 8: __('其他')}, formatter: Table.api.formatter.normal, searchable:false, visible:false},
						{field: 'agentcompany', title: __('代理机构'), searchable:false, visible:false},
						{field: 'noticetime', title: __('公告发布时间'), formatter: Table.api.formatter.datetime, datetimeFormat:'YYYY-MM-DD', searchable:false, visible:false},
						{field: 'bidopentime', title: __('开标时间'), formatter: Table.api.formatter.datetime, datetimeFormat:'YYYY-MM-DD', searchable:false, visible:false},
                        {field: 'biddercompany', title: __('中标单位'), operate: 'LIKE', align:'left'},
						{field: 'fundingsource', title: __('资金来源'), searchable:false, visible:false},
						{field: 'starttime', title: __('采购时间'), formatter: Table.api.formatter.datetime, datetimeFormat:'YYYY-MM-DD', defaultValue:Config.year?Config.year+'-01-01 - '+Config.year+'-12-31':'', extend: "data-locale='"+ JSON.stringify({format:'YYYY-MM-DD'})+"'"+" autocomplete='off'", operate: 'RANGE', addclass: 'datetimerange', sortable: true},
						{field: 'paymenttime', title: __('付款日期'), formatter: Table.api.formatter.datetime, datetimeFormat:'YYYY-MM-DD', extend: "data-locale='"+ JSON.stringify({format:'YYYY-MM-DD'})+"'"+" autocomplete='off'", operate: 'RANGE', addclass: 'datetimerange', visible:false},
						{field: 'payments.0.paymenttime', title: __('付款日期'), formatter: Table.api.formatter.datetime, datetimeFormat:'YYYY-MM-DD', extend: "data-locale='"+ JSON.stringify({format:'YYYY-MM-DD'})+"'"+" autocomplete='off'", operate: 'RANGE', addclass: 'datetimerange', sortable: true, searchable:false},
						{field: 'totalmoney', title: __('预算金额'), searchable:false, visible:false, formatter: function(value, row, index){
							if(value < 1000) return value;
							if(Number.isInteger(value)) {
								return String(value).replace(/(?!^)(?=(\d{3})+$)/g, ',');
							}else{
								return String(value).replace(/(?!^)(?=(\d{3})+\.)/g, ',');
							}
						}},
						{field: 'biddermoney', title: __('中标金额'), sortable: true, searchable:false, align:'right', formatter: function(value, row, index){
							if(value < 1000) return value;
							if(Number.isInteger(value)) {
								return String(value).replace(/(?!^)(?=(\d{3})+$)/g, ',');
							}else{
								return String(value).replace(/(?!^)(?=(\d{3})+\.)/g, ',');
							}
						}},
						{field: 'lawyerletter', title: __('律师审核意见书'), formatter: Table.api.formatter.file, searchable:false, visible:false},
						{field: 'contracttime', title: __('合同签订日期'), formatter: Table.api.formatter.datetime, datetimeFormat:'YYYY-MM-DD', searchable:false, visible:false},
						{field: 'endtime', title: __('完成时间'), formatter: Table.api.formatter.datetime, datetimeFormat:'YYYY-MM-DD', searchable:false, visible:false},
						{title: __('支付方式'), searchable:false, visible:false},
                        {field: 'paymenttimes', title: __('付款次数'), sortable: true, searchable:false, align:'right'},
						{field: 'payments.length', title: __('已付次数'), sortable: true, searchable:false, align:'right'},
						{field: 'status', title: __('项目进度'), searchList: {0: __('未开始'), 1: __('采购中'), 2: __('实施中'), 3: __('项目完成')},formatter: Table.api.formatter.normal},
						{field: 'execute_rate', title: __('项目执行进度'), searchable:false, visible:false},
						{field: 'admin.nickname', title: __('录入人'), operate: 'LIKE'},
						{field: 'warranty_period', title: __('质保期限'), searchable:false, visible:false},
						{field: 'supervision_depart', title: __('监理单位'), searchable:false, visible:false},
						{field: 'supervision_report', title: __('监理报告'), formatter: Table.api.formatter.file, searchable:false, visible:false},
						{field: 'audit_depart', title: __('工程审计单位'), searchable:false, visible:false},
						{field: 'audit_report', title: __('工程审计报告'), formatter: Table.api.formatter.file, searchable:false, visible:false},
						{field: 'checkreport', title: __('验收资料'), formatter: Table.api.formatter.file, searchable:false, visible:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, buttons:[
								{
									name: 'payment',
									title: __('付款'),
									text:__('付款'),
									classname: 'btn btn-xs btn-primary btn-dialog',
									url: $.fn.bootstrapTable.defaults.extend.pay_url
								}
							],formatter: Table.api.formatter.operate}
                    ]
                ],
				queryParams:function (params) {
					queryparams = params;
					return params;
				}
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
			
			// 续费
            $(document).on('click', '.btn-renew', function () {
                var ids = Table.api.selectedids(table);
				Layer.confirm(
                        __('你确定要续费吗?'),
                        {icon: 3, title: __('Warning'), shadeClose: true, btn: [__('OK'), __('Cancel')]},
                        function (index) {
                            Fast.api.ajax({
								url: "project/renew",
								type: "post",
								data: {ids: ids.join(',')},
							}, function () {
								table.bootstrapTable('refresh', {});
								Layer.close(index);
							});
                        }
                    );
            });
			
			// 导出
            $(document).on('click', '.btn-export', function () {
					var filter = queryparams.filter;
					var op = queryparams.op;
					var sort = queryparams.sort;
					var order = queryparams.order;
					/* table.one('post-body.bs.table', function () {
						require(['tableexport'], function () {
							table.tableExport($.extend({}, $.fn.bootstrapTable.defaults.exportOptions, {
								type: 'excel',
								escape: false
							}));
						});
						table.bootstrapTable('togglePagination', {});
					});
					table.bootstrapTable('togglePagination', {}); */
					location.href="export?sort="+sort+"&order="+order+"&filter="+filter+"&op="+op;
			});	
        },
        add: function () {
			$(document).on("change", "#procuretype", function () {
                    var value = $(this).val();
					if(value == 1 || value == 2 || value == 3 || value == 4 || value == 5 || value == 6 || value == 8)
					{
						$('#agentcompany').show();
						$('#biddercompany').show();
						$('#noticetime').show();
						$('#contracttime').show();
						$('#bidding').show();
						$('#rfp').show();
						$('#acceptance').show();
						$('#lawyerletter').show();
						$('#contract').show();
					}
					else if(value == 7)
					{
						$('#agentcompany').hide();
						$('#biddercompany').show();
						$('#lawyerletter').show();
						$('#contract').show();
						$('#contracttime').show();
						$('#noticetime').hide();
						$('#bidding').hide();
						$('#rfp').hide();
						$('#acceptance').hide();
					}
					else
					{
						$('#agentcompany').hide();
						$('#biddercompany').hide();
						$('#lawyerletter').hide();
						$('#contract').hide();
						$('#contracttime').hide();
						$('#noticetime').hide();
						$('#bidding').hide();
						$('#rfp').hide();
						$('#acceptance').hide();
					}
			});
			
			$(document).on("change", "#c-paymenttimes", function () {
				var value = $(this).val();
				for(var i=1; i<=10; i++)
				{
					$('#paymentimes-'+i).hide();
				}
				for(var i=1; i<=value; i++)
				{
					$('#paymentimes-'+i).show();
				}
            });
			
			$(document).on("change", "input[name='row[supervise]']", function () {
				var isChecked = $(this).is(':checked');
				if(isChecked==true)
				{
					$('#supervise').show();
				}
				else
				{
					$('#supervise').hide();
				}
			});
			
			$(document).on('blur',".paymentmoney", function(){
				var biddermoney = $('#c-biddermoney').val();
				var pay_money = $(this).val();
				if(biddermoney && pay_money)
				{
					var pay_rate = (pay_money*100/biddermoney).toFixed(2);
					$(this).parents('.paymentimes').find('.pay-rate').html(pay_rate+'%');
					
					var leiji_pay_money = 0;
					$('.paymentimes').each(function(){
						var pay_money = $(this).find('.paymentmoney').val();
						if(pay_money)
						{
							leiji_pay_money += parseInt(pay_money);
							var leiji_pay_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
							$(this).find('.total-pay-rate').html(leiji_pay_rate+'%');
						}
					});
					$('.execute_rate').html((leiji_pay_money*100/biddermoney).toFixed(2)+'%');
				}
			});
			
			$(document).on('blur','input[name="row[biddermoney]"]', function(){
				var biddermoney = Number($(this).val());
				var leiji_pay_money = 0;
				$('.paymentimes').each(function(){
					var pay_money = $(this).find('.paymentmoney').val();
					if(pay_money)
					{
						var pay_rate = 0.00;
						var leiji_pay_rate = 0.00;
						if(biddermoney)
						{
							pay_rate = (pay_money*100/biddermoney).toFixed(2);
							$(this).find('.pay-rate').html(pay_rate+'%');
						
							leiji_pay_money += parseInt(pay_money);
							leiji_pay_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
						}
						$(this).find('.total-pay-rate').html(leiji_pay_rate+'%');
					}
				});
				var execute_rate = 0.00;
				if(biddermoney)
				{
					execute_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
				}
				$('.execute_rate').html(execute_rate+'%');
			});
			
			$(document).on('change','select[name="row[procuredepart]"]',function(){
				var depart = $('.filter-option-inner-inner').html();
				depart = depart.replace('├ ','');
				$('select[name="row[procuredepart]"]').parent().find('.filter-option-inner-inner').html(depart);
			});
			
			$(document).on('blur','input[type="number"]', function(){
				var money = Number($(this).val());
				$(this).val(money.toFixed(2));
			});	
			
			$(document).on('click','button[type="reset"]', function(){
				var index = parent.Layer.getFrameIndex(window.name);
				parent.Layer.close(index);
			});	
			
            Form.api.bindevent($("form[role=form]"), function(data, ret){
				location.reload();
				Backend.api.addtabs(ret.url, '项目列表');
			});
        },
        edit: function () {
			$(document).on("change", "#procuretype", function () {
                    var value = $(this).val();
					if(value == 1 || value == 2 || value == 3 || value == 4 || value == 5 || value == 6 || value == 8)
					{
						$('#agentcompany').show();
						$('#biddercompany').show();
						$('#noticetime').show();
						$('#contracttime').show();
						$('#bidding').show();
						$('#rfp').show();
						$('#acceptance').show();
						$('#lawyerletter').show();
						$('#contract').show();
					}
					else if(value == 7)
					{
						$('#agentcompany').hide();
						$('#biddercompany').show();
						$('#lawyerletter').show();
						$('#contract').show();
						$('#contracttime').show();
						$('#noticetime').hide();
						$('#bidding').hide();
						$('#rfp').hide();
						$('#acceptance').hide();
					}
					else
					{
						$('#agentcompany').hide();
						$('#biddercompany').hide();
						$('#lawyerletter').hide();
						$('#contract').hide();
						$('#contracttime').hide();
						$('#noticetime').hide();
						$('#bidding').hide();
						$('#rfp').hide();
						$('#acceptance').hide();
					}
			});
			
			$(document).on("change", "#c-paymenttimes", function () {
                    var value = $(this).val();
					for(var i=1; i<=10; i++)
					{
						$('#paymentimes-'+i).hide();
					}
					for(var i=1; i<=value; i++)
					{
						$('#paymentimes-'+i).show();
					}
                });
			
			$(document).on("change", "input[name='row[supervise]']", function () {
				var isChecked = $(this).is(':checked');
				if(isChecked==true)
				{
					$('#supervise').show();
				}
				else
				{
					$('#supervise').hide();
				}
			});
				
			$(document).on('blur',".paymentmoney", function(){
				var biddermoney = $('#c-biddermoney').val();
				var pay_money = $(this).val();
				if(biddermoney && pay_money)
				{
					var pay_rate = (pay_money*100/biddermoney).toFixed(2);
					$(this).parents('.paymentimes').find('.pay-rate').html(pay_rate+'%');
					
					var leiji_pay_money = 0;
					$('.paymentimes').each(function(){
						var pay_money = $(this).find('.paymentmoney').val();
						if(pay_money)
						{
							leiji_pay_money += parseInt(pay_money);
							var leiji_pay_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
							$(this).find('.total-pay-rate').html(leiji_pay_rate+'%');
						}
					});
					$('.execute_rate').html((leiji_pay_money*100/biddermoney).toFixed(2)+'%');
				}
			});
			
			$(document).on('blur','input[name="row[biddermoney]"]', function(){
				var biddermoney = Number($(this).val());
				var leiji_pay_money = 0;
				$('.paymentimes').each(function(){
					var pay_money = $(this).find('.paymentmoney').val();
					if(pay_money)
					{
						var pay_rate = 0.00;
						var leiji_pay_rate = 0.00;
						if(biddermoney)
						{
							pay_rate = (pay_money*100/biddermoney).toFixed(2);
							$(this).find('.pay-rate').html(pay_rate+'%');
						
							leiji_pay_money += parseInt(pay_money);
							leiji_pay_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
						}
						$(this).find('.total-pay-rate').html(leiji_pay_rate+'%');
					}
				});
				var execute_rate = 0.00;
				if(biddermoney)
				{
					execute_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
				}
				$('.execute_rate').html(execute_rate+'%');
			});
			
			$(document).on('change','select[name="row[procuredepart]"]',function(){
				var depart = $('.filter-option-inner-inner').html();
				depart = depart.replace('├ ','');
				$('select[name="row[procuredepart]"]').parent().find('.filter-option-inner-inner').html(depart);
			});
			
			$(document).on('blur','input[type="number"]', function(){
				var money = Number($(this).val());
				$(this).val(money.toFixed(2));
			});
			
			$(document).on('click','button[type="reset"]', function(){
				var index = parent.Layer.getFrameIndex(window.name);
				parent.Layer.close(index);
			});	
			
            Controller.api.bindevent();
			
			setTimeout(function(){
				var depart = $('select[name="row[procuredepart]"]').parent().find('.filter-option-inner-inner').html();
				depart = depart.replace('├ ','');
				$('select[name="row[procuredepart]"]').parent().find('.filter-option-inner-inner').html(depart);
			}, 1000);
			
			
        },
		pay: function () {
			$(document).on("change", "#c-paymenttimes", function () {
                    var value = $(this).val();
					for(var i=1; i<=10; i++)
					{
						$('#paymentimes-'+i).hide();
					}
					for(var i=1; i<=value; i++)
					{
						$('#paymentimes-'+i).show();
					}
                });
			
			$(document).on('blur',".paymentmoney", function(){
				var biddermoney = $('#c-biddermoney').val();
				var pay_money = $(this).val();
				if(biddermoney && pay_money)
				{
					var pay_rate = (pay_money*100/biddermoney).toFixed(2);
					$(this).parents('.paymentimes').find('.pay-rate').html(pay_rate+'%');
					
					var leiji_pay_money = 0;
					$('.paymentimes').each(function(){
						var pay_money = $(this).find('.paymentmoney').val();
						if(pay_money)
						{
							leiji_pay_money += parseInt(pay_money);
							var leiji_pay_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
							$(this).find('.total-pay-rate').html(leiji_pay_rate+'%');
						}
					});
					$('.execute_rate').html((leiji_pay_money*100/biddermoney).toFixed(2)+'%');
				}
			});
			
			$(document).on('blur','input[name="row[biddermoney]"]', function(){
				var biddermoney = Number($(this).val());
				var leiji_pay_money = 0;
				$('.paymentimes').each(function(){
					var pay_money = $(this).find('.paymentmoney').val();
					if(pay_money)
					{
						var pay_rate = 0.00;
						var leiji_pay_rate = 0.00;
						if(biddermoney)
						{
							pay_rate = (pay_money*100/biddermoney).toFixed(2);
							$(this).find('.pay-rate').html(pay_rate+'%');
						
							leiji_pay_money += parseInt(pay_money);
							leiji_pay_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
						}
						$(this).find('.total-pay-rate').html(leiji_pay_rate+'%');
					}
				});
				var execute_rate = 0.00;
				if(biddermoney)
				{
					execute_rate = (leiji_pay_money*100/biddermoney).toFixed(2);
				}
				$('.execute_rate').html(execute_rate+'%');
			});
			
			$(document).on('blur','input[type="number"]', function(){
				var money = Number($(this).val());
				$(this).val(money.toFixed(2));
			});
			
			$(document).on('click','button[type="reset"]', function(){
				var index = parent.Layer.getFrameIndex(window.name);
				parent.Layer.close(index);
			});
			
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});